<?php
/**
 * Created by PhpStorm.
 * User: mengkang <i@mengkang.net>
 * Date: 2019/10/2 下午3:37
 */


$uri = "/upload/image/2019/0921/1569075837628814.jpeg";
$host = "static.mengkang.net";
$port = 80;

$filename = pathinfo($uri,PATHINFO_BASENAME);


$httpRequest = sprintf("GET %s HTTP/1.1\r\nHost: %s\r\nConnection: Close\r\n\r\n", $uri, $host);

$address = gethostbyname($host);

/**
 * AF_UNIX     本地通讯
 * AF_INET     TCP/IP – IPv4
 * AF_INET6    TCP/IP – IPv6
 *
 * SOCK_STREAM TCP 字节流
 * SOCK_DGRAM  UDP 数据报
 * SOCK_RAW    原始套接字
 *
 * getprotobyname('tcp') 6  == SOL_TCP
 */
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
    throw new RuntimeException("socket_create() failed: reason: " . socket_strerror(socket_last_error()));
}

$result = socket_connect($socket, $address, $port);
if ($result === false) {
    throw new RuntimeException ("socket_connect() failed: reason: ($result) " . socket_strerror(socket_last_error($socket)));
}

socket_write($socket, $httpRequest, strlen($httpRequest));

$isHeader = true;
while ($data = socket_read($socket, 2048)) {

    if ($data === false) {
        throw new RuntimeException ("socket_recv() failed; reason: " . socket_strerror(socket_last_error($socket)));
    }

    if (strlen($data) <= 0) {
        break;
    }

    if ($isHeader) {
        $data = substr($data, strpos($data, "\r\n\r\n") + 4);
        file_put_contents($filename,""); // 清空下文件
        $isHeader = false;
    }

    file_put_contents($filename, $data, FILE_APPEND);
}

socket_close($socket);